<template>
    <div class="medal-page">
        <el-card shadow="never" class="filter">
            <el-form
                :model="form"
                label-suffix="："
                label-width="90px"
                label-position="right"
                ref="form">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="课程标题" prop="name">
                            <el-input v-model="form.name" placeholder class="input-width"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="课程状态" prop="status">
                            <el-select v-model="form.status" clearable class="input-width" @change="fetchData">
                                <el-option label="上架" value="1"></el-option>
                                <el-option label="下架" value="2"></el-option>
                                <el-option label="即将上线" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="border-bottom"></div>
                <div class="mt-4 text-center">
                    <el-button type="primary" @click="onSubmit">搜索</el-button>
                    <el-button type="text" @click="onResetFilters">清空筛选条件</el-button>
                </div>
            </el-form>
        </el-card>
        <el-card shadow="never" class="mt-4">
            <el-button type="primary" @click="onAddClick">新增</el-button>
            <div class="mt-4" v-loading="loading">
                <el-table :data="data">
                    <el-table-column label="课程标记" prop="mark"/>
                    <el-table-column label="绑定的岗位角色" prop="label"/>
                    <el-table-column label="课程名称" prop="name"/>
                    <el-table-column label="简介" prop="introduction"/>
                    <el-table-column label="课程状态">
                        <template slot-scope="{row}">
                            {{ row.is_near_shelf ? '即将上线' : row.is_shelf ? '已上架' : '已下架' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="{row}">
                            <el-button type="text" @click="getCourseBind(row.id)">选择企业设置课程权限</el-button>
                            <el-button type="text" @click="onStatusClick(1, row)">
                                {{ row.is_shelf ? '下架课程' : '上架课程' }}
                            </el-button>
                            <el-button
                                v-if="!row.is_near_shelf && !row.is_shelf"
                                type="text"
                                @click="onStatusClick(2, row)">设置即将上线</el-button>
                            <el-button type="text" @click="toChapter(row)">设置课程章节内容</el-button>
                            <el-button type="text" @click="onAddClick(row)">编辑</el-button>
                            <el-button type="text" @click="onDeleteClick(row)" class="red-color">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="totalElements > 0" class="footer mt-4 text-center">
                <el-pagination
                    class="center"
                    @size-change="fetchData"
                    @current-change="fetchData"
                    :current-page.sync="form.page"
                    :page-size="form.size"
                    :page-sizes="[10, 25, 50]"
                    layout="total, prev, pager, next, sizes, jumper"
                    :total="totalElements">
                </el-pagination>
            </div>
        </el-card>

        <el-dialog title="企业列表" :visible.sync="visible" width="60%">
            <div class="flex">
                <el-input v-model="companyForm.keyword" placeholder class="input-width"></el-input>
                <el-button type="primary" @click="getCompany">搜索</el-button>
            </div>
            <el-table :data="companyList" v-loading="loading">
                <el-table-column label="企业名称" prop="name"/>
                <el-table-column label="企业账号" prop="account"/>
                <el-table-column label="状态">
                    <template slot-scope="{row}">
                        {{ row.status === 1 ? '有效' : '无效' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="{row}">
                        <el-button
                            v-if="selectCompany.indexOf(row.id) === -1"
                            type="text"
                            @click="onBindCompany(row)">设置课程权限</el-button>
                        <el-button v-else type="success">已设置</el-button>
                        <el-button type="text" @click="getUser(row.id)">选择企业下用户</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="flex justify-center">
                <el-pagination
                    v-if="companyForm.total"
                    class="center"
                    @size-change="getCompany"
                    @current-change="getCompany"
                    :current-page.sync="companyForm.page"
                    :page-size.sync="companyForm.size"
                    :page-sizes="[10, 25, 50]"
                    layout="total, prev, pager, next, sizes, jumper"
                    :total="companyForm.total">
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog title="用户列表" :visible.sync="userVisible" width="60%">
            <div class="flex">
                <el-input v-model="userKeyword" placeholder class="input-width"></el-input>
                <el-button type="primary" @click="getUser">搜索</el-button>
                <el-button :disabled="!selectUser.length" type="primary" @click="onUserBindCourse">绑定</el-button>
                <el-button @click="resetUserSelect">取消全部选择</el-button>
            </div>
            <el-table
                ref="userTable"
                :data="userList"
                v-loading="loading"
                @selection-change="handleSelectionChange"
                :row-key="(row) => row.id">
                <el-table-column
                    type="selection"
                    width="50"
                    reserve-selection
                    :selectable="(row) => !row.is_open"/>
                <el-table-column label="用户名称" prop="name"/>
                <el-table-column label="用户邮箱" prop="email"/>
                <el-table-column label="状态">
                    <template slot-scope="{row}">
                        {{ row.status === 1 ? '有效' : '无效' }}
                    </template>
                </el-table-column>
                <el-table-column label="是否绑定">
                    <template slot-scope="{row}">
                        {{ row.is_open ? '是' : '未绑定' }}
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="flex justify-center">
                <el-pagination
                    v-if="userForm.total"
                    class="center"
                    @size-change="getUser"
                    @current-change="getUser"
                    :current-page.sync="userForm.page"
                    :page-size.sync="userForm.size"
                    :page-sizes="[10, 25, 50]"
                    layout="total, prev, pager, next, sizes, jumper"
                    :total="userForm.total">
                </el-pagination>
            </div>
        </el-dialog>
    </div>
</template>

<script>

export default {
    components: {
    },
    mixins: [require('@/mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            data: [],
            form: {
                page: 1,
                size: 25,
                name: '',
                status: '',
            },
            totalElements: 0,

            visible: false,
            companyList: [],
            selectCompany: '',
            selectCourse: '',
            companyForm: {
                page: 1,
                size: 10,
                total: 0,
                keyword: '',
            },

            userVisible: false,
            userList: [],
            selectUser: '',
            userKeyword: '',
            userForm: {
                page: 1,
                size: 10,
                total: 0,
                companyId: '',
            },
        };
    },
    methods: {
        onSubmit() {
            this.form.page = 1;
            this.fetchData();
        },
        onResetFilters() {
            this.$refs.form.resetFields();
            this.onSubmit();
        },
        fetchData() {
            this.loading = true;
            API.get('merit_course/page', { params: this.form }).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => this.loading = false);
        },

        onAddClick(row) {
            const params = row && row.id ? { id: row.id } : undefined;
            this.$router.push({
                name: 'Medal.Form',
                params,
            });
        },

        toChapter(row) {
            this.$router.push({
                name: 'Chapter.List',
                query: {
                    id: row.id,
                },
            });
        },

        onDeleteClick(row) {
            $ele.$confirm('是否删除此勋章课程？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.delete(`merit_course/${row.id}`).then(() => {
                    this.fetchData();
                    $ele.$message.success('删除成功');
                }).finally(() => this.loading = false);
            }).catch();
        },

        onStatusClick(type, row) {
            const url = type === 1 ? `merit_course/shelf/${row.id}` : `merit_course/soon-online/${row.id}`;
            this.loading = true;
            API.put(url).then(() => {
                this.fetchData();
                $ele.$message.success('操作成功');
            }).finally(() => this.loading = false);
        },

        getCourseBind(id) {
            API.get(`merit_course/companys/${id}`).then(res => {
                const selectCompany = [];
                for (const item of res) {
                    if (item.is_binding) selectCompany.push(item.id);
                }
                this.selectCompany = selectCompany;
                this.selectCourse = id;
                this.visible = true;
            });
        },

        getCompany() {
            API.get('company', {params: this.companyForm}).then(res => {
                this.companyList = res.content;
                this.companyForm.total = res.pagination.total;
            });
        },

        onBindCompany(e) {
            $ele.$confirm('是否为该企业绑定勋章课程?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.put('merit_course/company-open', {
                    company_id: e.id,
                    merit_course_id: this.selectCourse,
                }).then(() => {
                    $ele.$message.success('绑定成功');
                    this.getCourseBind(this.selectCourse);
                }).finally(() => this.loading = false);
            }).catch(() => {});
        },

        // 勋章课绑定用户 start
        getUser(companyId) {
            if (companyId) this.userForm.companyId = companyId;
            this.loading = true;
            API.get('user', {
                params: {
                    ...this.userForm,
                    keyword: this.userKeyword,
                    meritCourseId: this.selectCourse,
                },
            }).then(res => {
                this.userList = res.content;
                this.userForm.total = res.pagination.total;
                if (companyId) this.userVisible = true;
            }).finally(() => this.loading = false);
        },

        onUserBindCourse() {
            $ele.$confirm('是否为该用户绑定勋章课程?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.post('user/gift-merit-course', {
                    merit_course_id: this.selectCourse,
                    user_ids: this.selectUser,
                }).then(() => {
                    $ele.$message.success('绑定成功');
                    this.resetUserSelect();
                    this.getUser();
                }).finally(() => this.loading = false);
            }).catch(() => {});
        },

        handleSelectionChange(val) {
            if (val.length) {
                this.selectUser = val.map(item => item.id);
            } else this.selectUser = [];
        },

        resetUserSelect() {
            this.$refs.userTable.clearSelection();
        },
    },
    mounted() {
        this.fetchData();
        this.getCompany();
    },
};
</script>

<style lang="scss" scoped>
.medal-page {
    .input-width {
        max-width: 300px;
    }
}
</style>
